package com.kelvin.backend.common.web.entity.page;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.io.Serializable;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>Title: PageEntity</p>
 * <p>Description: </p>
 *
 * @author Kelvin.Chen
 * @datetime 2021/7/9 14:59
 */
public class PageEntity implements Serializable {

    /**
     * 当前页数
     */
    private int page;

    /**
     * 数目大小
     */
    private int size;

    /**
     * 排序字段
     */
    List<OrderField> orderFields;

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getSize() {
        return size;
    }

    public void setSize(int size) {
        this.size = size;
    }

    public Page initPage() {
        Page page = new Page();
        page.setCurrent(this.page);
        page.setSize(this.size);

        if (ObjectUtil.isNotEmpty(this.orderFields)) {
            page.setOrders(this.orderFields.stream().map(orderField -> {
                OrderItem orderItem;
                String column = StrUtil.toUnderlineCase(orderField.getField());
                if (orderField.getOrder() == 0) {
                    orderItem = OrderItem.asc(column);
                } else {
                    orderItem = OrderItem.desc(column);
                }
                return orderItem;
            }).collect(Collectors.toList()));
        }
        return page;
    }

}
